package com.example.tinker;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.e("运行了","Tinker运行起来了");
    }

    public void test(View view) {
        TestTinker.testTow();
    }

    public void fixManager(View view) {

        //  第一步获取到所有的修复包、补丁
        File odex = this.getDir("out.dex", Context.MODE_PRIVATE);
        // 定义 out.dex  补丁名字
        String name = "out.dex";
        //  获取到补丁复制过去的完整File 对象  /data/user/0/com.example.tinker/app_out.dex/out.dex
        File file = new File(odex.getAbsolutePath(),name);
        //  复制过去的时候先判断一下目的地是否存在这个名字的文件
        if (file.exists()) {
            file.delete();//  删除重名
        }
        String filePath = file.getAbsolutePath();
        //创建文件输入输出流
        FileInputStream is = null;
        FileOutputStream os = null;
        try {
            //  起点
            is = new FileInputStream(new File(Environment.getExternalStorageDirectory(),name));
            //  终点
            os = new FileOutputStream(filePath);
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer,0,len);
            }
            File f = new File(filePath);
            //  去加载dex文件  然后将补丁的dex 文件与当前APP的dex文件进行合并
            FixManager.loadDex(this);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}